package com.example.admin_oa.shiro;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.admin_oa.model.mapper.SysUserMapper;
import com.example.admin_oa.model.mapper.SysUserRoleMapper;
import com.example.comment_oa.pojos.SysUser;
import com.example.comment_oa.pojos.SysUserRole;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class AccoutRealm extends AuthorizingRealm {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof JwtToken;
    }
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
        sysUser.setUserPassword(null);
        Set<String> rolesByname = sysUserRoleMapper.selectAllByUserId(sysUser.getUserId());
        Set<String> userPermission = sysUserMapper.findUserPermissionByid(sysUser.getUserId());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(rolesByname);
        info.setStringPermissions(userPermission);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectByUserId(sysUser.getUserId());
        stringRedisTemplate.delete("roles");
        stringRedisTemplate.delete("permission");
        stringRedisTemplate.opsForValue().set("roles", JSON.toJSONString(sysUserRoles));
        stringRedisTemplate.opsForValue().set("permission",JSON.toJSONString(userPermission));
        info.getStringPermissions().forEach(e-> System.err.println(e));
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //把他传过来的token转成自己写的jwtToken
        JwtToken jwtToken=(JwtToken) authenticationToken;
        //获取token
        String jwt = (String)jwtToken.getPrincipal();
        //解析jwt
        Claims claims = JwtUtil.parseJWT(jwt);
        //获取username
        String username = claims.getId();
        QueryWrapper<SysUser> wrapper=new QueryWrapper<>();
        wrapper.eq("user_no",username);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if(sysUser==null){
            QueryWrapper<SysUser> wrapper1=new QueryWrapper<>();
            wrapper1.eq("user_phone",username);
            SysUser sysUser1 = sysUserMapper.selectOne(wrapper1);
            jwtToken.setSysUser(sysUser1);
            if(sysUser1==null){
                return null;
            }else{
                return new SimpleAuthenticationInfo(sysUser1,sysUser1.getUserPassword(),getName());
            }
        }else{
            jwtToken.setSysUser(sysUser);
            return new SimpleAuthenticationInfo(sysUser,sysUser.getUserPassword(),getName());
        }
    }
}
